package com.freeseed.config.auth;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.freeseed.model.entity.User;
import com.freeseed.model.mapper.UserMapper;
import com.freeseed.util.TokenCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class MyAuthenticationSuccessHandler extends JSONAuthentication implements AuthenticationSuccessHandler {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {

        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        SecurityContextHolder.getContext().setAuthentication(authentication);
        log.info("userDetails: {}",userDetails);

        String token = TokenCache.getTokenFromCache(userDetails.getUsername());
        if(token == null){
            log.info("尚未有Token，生成新的Token");
            token = jwtTokenUtil.generateToken(userDetails);
            //把新的token存储到缓存中
            TokenCache.setToken(userDetails.getUsername(),token);
            log.info("This is new Token: {}",token);
        }
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_email",userDetails.getUsername()));
        Map<String,Object> map = new HashMap<>();
        map.put("email",userDetails.getUsername());
        map.put("auth",userDetails.getAuthorities());
        map.put("userInfo",user);
        map.put("token",token);
        R<Map<String,Object>> data = R.ok(map);
        this.WriteJSON(httpServletRequest,httpServletResponse,data);
    }
}
